package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.GetLeanPaintKpiReportService;
import com.ugoodtech.mdcc.client.service.MyReportService;
import com.ugoodtech.mdcc.client.service.UserLogService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.StationtResponseReport.StationtResponseReport;
import com.ugoodtech.mdcc.core.repository.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.List;

@Api(description = "我的报告相关接口")
@RestController
@RequestMapping("/myReport")
public class MyReportController {

    @Autowired
    private MyReportService myReportService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AnswerDicRepository answerDicRepository;

    @Autowired
    private OperationalDataAnalysisRepository operationalDataAnalysisRepository;

    @Autowired
    private StationColorReportTempRepository stationColorReportTempRepository;

    @Autowired
    private StationRegularServiceReportUnFinshedRepository stationRegularServiceReportUnFinshedRepository;

    @Autowired
    private StationLeanPaintReportTempRepository stationLeanPaintReportTempRepository;

    @Autowired
    private UserLogService userLogService;

//    @ApiOperation("根据ID获取我的报告")
//    @RequestMapping(value = "getReport", method = RequestMethod.GET)
//    public JsonResponse getReport(Principal principal,
//                                  @ApiParam("报告的状态ID") @RequestParam(value = "reportId") Long reportId,
//                                  @ApiParam("分类") @RequestParam(value = "category") QuestionPaper.QuestionPaperCategory category) {
//        User clientUser = userRepository.findByUsername(principal.getName());
//        if (clientUser == null) {
//            return JsonResponse.errorResponseWithError("500", "未找到此用户");
//        }
//        return myReportService.getReport(clientUser.getId(), reportId, category);
//    }


//    @ApiOperation("获取我的技术颜色报告")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
//            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
//    })
//    @RequestMapping(value = "getStationTechColorReport", method = RequestMethod.GET)
//    public JsonResponse getStationTechColorReport(Principal principal,
//                                                  @ApiParam("报告的状态:complete,unfinished") @RequestParam(value = "type") String type,
//                                                  Pageable pageable) {
//        User clientUser = userRepository.findByUsername(principal.getName());
//        if (clientUser == null) {
//            return JsonResponse.errorResponseWithError("500", "未找到此用户");
//        }
//        Page<StationtResponseReport> page = myReportService.getStationTechColorReport(clientUser.getId(), pageable, type);
//        return JsonResponse.successResponseWithPageData(page);
//    }

    @ApiOperation("获取我的精益钣金报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getStationLeanPaintReport", method = RequestMethod.GET)
    public JsonResponse getStationLeanPaintReport(Principal principal,
                                                  @ApiParam("报告的状态:complete,unfinished") @RequestParam(value = "type", required = false) String type,
                                                  Pageable pageable) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
//        Page<StationtResponseReport> page = myReportService.getStationLeanPaintReport(clientUser.getId(), pageable, type);
        return myReportService.getMyPaintReport(clientUser, type, pageable);
    }

//    @ApiOperation("获取我的服务常规报告")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
//            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
//    })
//    @RequestMapping(value = "getStationServiceReport", method = RequestMethod.GET)
//    public JsonResponse getStationServiceReport(Principal principal,
//                                                @ApiParam("报告的状态:complete,unfinished") @RequestParam(value = "type") String type,
//                                                Pageable pageable) {
//        User clientUser = userRepository.findByUsername(principal.getName());
//        if (clientUser == null) {
//            return JsonResponse.errorResponseWithError("500", "未找到此用户");
//        }
//        Page<StationtResponseReport> page = myReportService.getStationServiceReport(clientUser.getId(), pageable, type);
//        return JsonResponse.successResponseWithPageData(page);
//    }

    ///////////////////////////////改///////////////////////////////////////


    @ApiOperation("获取计划中的常规服务报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getPlanServiceReport", method = RequestMethod.GET)
    public JsonResponse getPlanServiceReport(Principal principal, Pageable pageable) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        return myReportService.getPlanServiceReport(clientUser, pageable);
    }

    @ApiOperation("获取我的已提交报告-(不包括基础报告)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getMyCompleteReport", method = RequestMethod.GET)
    public JsonResponse getMyCompleteReport(Principal principal, Pageable pageable,
                                            @ApiParam("报告的类型：customer_report，service_report，" +
                                                    "techcolor_report，paint_report") @RequestParam(value = "category") String category) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        return myReportService.getMyReport(clientUser, pageable, category);
    }

    @ApiOperation("获取我的已提交的基础报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getMyAuditReport", method = RequestMethod.GET)
    public JsonResponse getMyAuditReport(Principal principal, Pageable pageable) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }

        return null;
    }

    @ApiOperation("获取我的暂存报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getMyUnFinshedReport", method = RequestMethod.GET)
    public JsonResponse getMyUnFinshedReport(Principal principal, Pageable pageable,
                                             @ApiParam("报告的类型：customer_report，service_report，" +
                                                     "techcolor_report，paint_report") @RequestParam(value = "category") String category) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        return myReportService.getMyUnFinshedReport(clientUser, pageable, category);
    }

    @Autowired
    private GetLeanPaintKpiReportService getLeanPaintKpiReportService;

    @ApiOperation("测试数据")
    @RequestMapping(value = "getAnswerDic", method = RequestMethod.GET)
    public JsonResponse getAnswerDic(Long stationId) {
        return JsonResponse.successResponseWithData(getLeanPaintKpiReportService.toArray(stationId, null));
    }

    @Autowired
    private UnitOperationsRepository unitOperationsRepository;

    @ApiOperation("测试数据")
    @RequestMapping(value = "getMonth", method = RequestMethod.GET)
    public JsonResponse getMonth(@ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId) {
        List<Object[]> obj = unitOperationsRepository.getMonth(stationId);
        return JsonResponse.successResponseWithData(obj);
    }

    @Autowired
    private StationReportUnFinshedRepository stationReportUnFinshedRepository;

    @ApiOperation("删除暂存报告")
    @RequestMapping(value = "delTempReport", method = RequestMethod.POST)
    public JsonResponse delTempReport(Principal principal, Long reportId) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        QStationReportTemp qStationReportTemp = QStationReportTemp.stationReportTemp;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReportTemp.deleted.eq(false));
        builder.and(qStationReportTemp.enabled.eq(true));
        builder.and(qStationReportTemp.id.eq(reportId));
        StationReportTemp stationReportTemp = stationReportUnFinshedRepository.findOne(builder);
        if (stationReportTemp == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
        }
        if (!stationReportTemp.getUser().getId().equals(clientUser.getId())) {
            return JsonResponse.errorResponseWithError("抱歉", "此报告不是你写的");
        }
        String reportCategort = stationReportTemp.getReportCategory();
        stationReportTemp.setDeleted(true);
        stationReportTemp.setEnabled(false);
        stationReportUnFinshedRepository.save(stationReportTemp);
        QStationColorReportTemp colorReportTemp;
        QStationLeanPaintReportTemp stationLeanPaintReportTemp;
        QStationRegularServiceReportUnFinshed stationRegularServiceReportUnFinshed;
        if (reportCategort.equals(Constants.TECHCOLOR_REPORT)) {
            colorReportTemp = QStationColorReportTemp.stationColorReportTemp;
            builder = new BooleanBuilder();
            builder.and(colorReportTemp.deleted.eq(false));
            builder.and(colorReportTemp.enabled.eq(true));
            builder.and(colorReportTemp.stationReportUnFinshed.id.eq(reportId));
            List<StationColorReportTemp> stationColorReportTempList = (List<StationColorReportTemp>) stationColorReportTempRepository.findAll(builder);
            for (StationColorReportTemp temp : stationColorReportTempList) {
                temp.setDeleted(true);
                temp.setEnabled(false);
                stationColorReportTempRepository.save(temp);
            }
            return JsonResponse.successResponse();
        }
        if (reportCategort.equals(Constants.SERVICE_REPORT)) {
            stationRegularServiceReportUnFinshed = QStationRegularServiceReportUnFinshed.stationRegularServiceReportUnFinshed;
            builder = new BooleanBuilder();
            builder.and(stationRegularServiceReportUnFinshed.deleted.eq(false));
            builder.and(stationRegularServiceReportUnFinshed.enabled.eq(true));
            builder.and(stationRegularServiceReportUnFinshed.stationReportTemp.id.eq(reportId));
            List<StationRegularServiceReportUnFinshed> regularServiceReportUnFinshedList = (List<StationRegularServiceReportUnFinshed>) stationRegularServiceReportUnFinshedRepository.findAll(builder);
            for (StationRegularServiceReportUnFinshed temp : regularServiceReportUnFinshedList) {
                temp.setDeleted(true);
                temp.setEnabled(false);
                stationRegularServiceReportUnFinshedRepository.save(temp);
            }
            return JsonResponse.successResponse();
        }
        if (reportCategort.equals(Constants.PAINT_REPORT)) {
            stationLeanPaintReportTemp = QStationLeanPaintReportTemp.stationLeanPaintReportTemp;
            builder = new BooleanBuilder();
            builder.and(stationLeanPaintReportTemp.deleted.eq(false));
            builder.and(stationLeanPaintReportTemp.enabled.eq(true));
            builder.and(stationLeanPaintReportTemp.stationReportUnFinshed.id.eq(reportId));
            List<StationLeanPaintReportTemp> paintReportTempList = (List<StationLeanPaintReportTemp>) stationLeanPaintReportTempRepository.findAll(builder);
            for (StationLeanPaintReportTemp temp : paintReportTempList) {
                temp.setDeleted(true);
                temp.setEnabled(false);
                stationLeanPaintReportTempRepository.save(temp);
            }
            //删除日志================================
//            userLogService.addUserLog(clientUser,null, LogConstants.operate_type_delete,LogConstants.operate_module_,null,null);
            return JsonResponse.successResponse();
        }
        return JsonResponse.errorResponseWithError("抱歉", "删除失败");
    }


}
